package com.android.driveuploader;

import android.app.IntentService;
import android.app.WallpaperManager;
import android.content.Context;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;


/**
 * Created by srikanthg on 9/5/14.
 */
public class WallpaperScheduler extends ScheduledThreadPoolExecutor {
    public WallpaperScheduler(int corePoolSize) {
        super(corePoolSize);
    }

    public void changeWallPapers(final Context context, final Drive service, final List downloadUrls, int period, TimeUnit timeUnit) {
        Runnable command = new Runnable() {
            @Override
            public void run() {
                /*Iterator<String> downloadUrl = downloadUrls.iterator();
                while (downloadUrl.hasNext()) {
                    try {
                        HttpResponse resp =
                                service.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrl.next()))
                                        .execute();
                        //return resp.getContent();
                        InputStream inputStream = resp.getContent();
                        WallpaperManager wpm = WallpaperManager.getInstance(context);
                        //wpm.setResource(file.toURI());
                        //InputStream ins = new URL(filePath).openStream();
                        //InputStream ins = new FileInputStream(file);
                        wpm.setStream(inputStream);
                    } catch (IOException e) {
                        // An error occurred.
                        e.printStackTrace();
                        //return null;
                    }
                }*/
               // Context context2 = getApp

                if(MyActivity.driveService != null) {
                    Log.i("WallpaperScheduler *****************", "Reached...");
                    TinyDB tinyDB = new TinyDB(context);
                    ArrayList<String> downloadUrls = tinyDB.getList("downloadUrls");
                    try {
                        int number = new Random().nextInt(downloadUrls.size() - 2) + 1;
                        HttpResponse resp =
                                MyActivity.driveService.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrls.get(number).toString()))
                                        .execute();
                        //return resp.getContent();
                        InputStream inputStream = resp.getContent();
                        WallpaperManager wpm = WallpaperManager.getInstance(context);
                        //wpm.setResource(file.toURI());
                        //InputStream ins = new URL(filePath).openStream();
                        //InputStream ins = new FileInputStream(file);
                        wpm.setStream(inputStream);
                        Log.d("************************", "Wallpaper changed!" + number);
                    } catch (IOException e) {
                        // An error occurred.
                        e.printStackTrace();
                        //return null;
                    }
                }
                else {
                    Log.i("WallpaperScheduler *****************", "Service may be null...");
                }
            }
        };

        //scheduleAtFixedRate(command, 0, period, timeUnit); // TODO: Actual working line.
        scheduleAtFixedRate(command, 0, 10, TimeUnit.SECONDS); //TODO: Hard-coded one.. Delete later
    }

    public void changeWallPapers(final Context applicationContext, ArrayList<String> downloadUrl, int i, TimeUnit minutes) {
        Runnable command = new Runnable() {
            @Override
            public void run() {
                TinyDB tinyDB = new TinyDB(applicationContext);
                String open_accountName = tinyDB.getString("open_accountName");
                Drive driveService = null;
                if (open_accountName != "") {
                    Log.i("open_account name: ", open_accountName);
                    GoogleAccountCredential credential = GoogleAccountCredential.usingOAuth2(applicationContext, Collections.singleton(DriveScopes.DRIVE));
                    credential.setSelectedAccountName(open_accountName);
                    driveService = new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
                } else {
                    Log.i("open_account name: null????????", open_accountName);
                }

                    if (driveService != null) {
                        Log.i("WallpaperScheduler *****************", "Reached...");
                        //TinyDB tinyDB = new TinyDB(context);
                        ArrayList<String> downloadUrls = tinyDB.getList("downloadUrls");
                        try {
                            int number = new Random().nextInt(downloadUrls.size() - 2) + 1;
                            HttpResponse resp =
                                    driveService.getRequestFactory().buildGetRequest(new GenericUrl(downloadUrls.get(number).toString()))
                                            .execute();
                            //return resp.getContent();
                            InputStream inputStream = resp.getContent();
                            WallpaperManager wpm = WallpaperManager.getInstance(applicationContext);
                            //wpm.setResource(file.toURI());
                            //InputStream ins = new URL(filePath).openStream();
                            //InputStream ins = new FileInputStream(file);
                            wpm.setStream(inputStream);
                            Log.d("************************", "Wallpaper changed!" + number);
                        } catch (IOException e) {
                            // An error occurred.
                            e.printStackTrace();
                            //return null;
                        }
                    } else {
                        Log.i("WallpaperScheduler *****************", "Service may be null...");
                    }
            }
        };
        //scheduleAtFixedRate(command, 0, 100, TimeUnit.SECONDS); //TODO: Hard-coded one.. Delete later

    }
}
